package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Override
    public Address findDefaultADdress() {
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getIsDefault,1);
        lqw.eq(Address::getUserId,UserHolder.get().getId() ); // 用户id

        Address address = addressMapper.selectOne(lqw);

        return address;
    }

    @Autowired
    private AddressMapper addressMapper;


    @Override
    public void setAddressDefault(Long id) {
//创建查询条件对象
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getUserId, UserHolder.get().getId());
        Address example = new Address();
        example.setIsDefault(0);
        addressMapper.update(example, lqw);


        Address address = addressMapper.selectById(id);
        address.setIsDefault(1);
        addressMapper.updateById(address);
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        addressMapper.deleteBatchIds(ids);
        List<Address> addresses = addressMapper.selectBatchIds(ids);
        for (Address address : addresses) {
            if(address.getIsDefault()==0){

            }
        }
    }

    @Override
    public void updateAddress(Address address) {
        address.setIsDefault(0);
        address.setUserId(UserHolder.get().getId());

        addressMapper.updateById(address);
    }

    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    @Override
    public void add(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        addressMapper.insert(address);
    }

    @Override
    public List<Address> findAll() {
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addresses = addressMapper.selectList(lqw);


        return addresses;
    }
}
